package cn.edu.scau.controller;

import cn.edu.scau.bean.ResultBean;
import cn.edu.scau.entity.*;
import cn.edu.scau.service.CustomerService;
import cn.edu.scau.service.MedicationrecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

@Api(tags = "用药记录控制器")
@RestController
@RequestMapping("medicationrecord")
public class MedicationrecordController {
    @Autowired
    MedicationrecordService medicationrecordService;
    @Autowired
    CustomerService customerService;
    /**
     * 查询所有用药记录信息
     * @return
     */
    @ApiOperation(value = "查询所有用药记录信息")
    @GetMapping(value = "/list")
    public ResultBean list(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "5")int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
       List<MedicationrecordShow> medicationrecordShows = medicationrecordService.selectAll();
        PageInfo<MedicationrecordShow> pageInfo = new PageInfo<MedicationrecordShow>(medicationrecordShows);
        ResultBean resultBean =new ResultBean(200,true,"查询所有用药记录信息~~~",pageInfo);
        return resultBean;
    }
    /**
     * 显示所根据记录编号，用户编号模糊查询
     * 基于前后端分离
     * @param
     * @return
     */
    @ApiOperation(value = "显示所根据记录编号，客户编号模糊查询,数据存储在hospital中")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query" ,name = "medicationRecordID" , value = "记录编号",dataType = "int"),
            @ApiImplicitParam(paramType = "query" ,name = "customerID" , value = "客户编号",dataType = "int")
    })
    @GetMapping(value = "/find")
//    @ResponseBody
    public ResultBean find(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "5")int pageSize,Integer medicationRecordID,Integer customerID){
        PageHelper.startPage(pageNum, pageSize);
        List<MedicationrecordShow> medicationrecordShows = medicationrecordService.findByMIdCId(medicationRecordID,customerID);
        PageInfo<MedicationrecordShow> pageInfo = new PageInfo<MedicationrecordShow>(medicationrecordShows);
        ResultBean r =new ResultBean(200,true,"查询所有用药记录信息~~~",pageInfo);
        return r;
    }

    /**
     * 根据记录账号查询记录信息
     * @param medicationrecordid
     * @return
     */
    @ApiOperation(value = "根据记录账号查询记录信息")
    @ApiImplicitParam(paramType = "path" ,name = "medicationrecordid" , value = "记录账号",dataType = "int")
    @ApiResponse(code = 200,message = "返回medicationrecord页面,数据存储在hospital中")
    @GetMapping(value = "/{medicationrecordid}")
//    @ResponseBody
    public ResultBean detail(@PathVariable("medicationrecordid") Integer medicationrecordid){
       Medicationrecord medicationrecord = medicationrecordService.selectByPrimaryKey(medicationrecordid);
        ResultBean r = new ResultBean(200, true, "查询成功", medicationrecord);
        //查不到
        if(medicationrecord==null) {
            r = new ResultBean(5008, false, "查询失败", null);
        }
        return r;
    }
    /**
     * 删除相应id的记录信息
     * @param medicationrecordid
     * @return
     */
    @ApiOperation(value = "删除相应id的记录信息")
    @DeleteMapping(value = "/delete/{medicationrecordid}")
//    @ResponseBody
    public ResultBean delete(@PathVariable("medicationrecordid") Integer medicationrecordid){
        ResultBean r = null;
        boolean flag = medicationrecordService.deleteByPrimaryKey(medicationrecordid);
        if(flag){
            r =new ResultBean(200,true,"删除成功",null);
        }else
        {
            r =new ResultBean(5005,false,"删除失败",null);
        }
        return r;
    }
    /**
     * 新增用药记录
     *
     * @return
     * @throws ParseException
     */
    @PostMapping(value = "/insert")
//    @ResponseBody
    public ResultBean insert(@Validated MedicationrecordConve medicationrecordConve, BindingResult bindingResult) {
        ResultBean r = null;
        if(bindingResult.hasErrors()){
            //方法一：将无法通过数据校验的信息，合并成一个字符串，返回给前端
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
            ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            //方法二：将所有无法通过数据校验的信息集合，直接返回给前端，让前端自行处理
            // r = new ResultBean(5004,false,"部门赋值失败",bindingResult.getFieldErrors());
            return r;
        }
        Medicationrecord medicationrecord = Medicationrecord.builder()
                .customerid(Integer.valueOf(medicationrecordConve.getCustomerid()))
                .medicationrecorddispenser(medicationrecordConve.getMedicationrecorddispenser())
                .medicationrecorddosage(medicationrecordConve.getMedicationrecorddosage())
                .medicationrecorddrugname(medicationrecordConve.getMedicationrecorddrugname())
                .medicationrecordid(null)
                .medicationrecordmethod(medicationrecordConve.getMedicationrecordmethod())
                .medicationrecordshipper(medicationrecordConve.getMedicationrecordshipper()).build();
        Customer customer = customerService.selectByPrimaryKey(medicationrecord.getCustomerid());
        if(customer!=null&&customer.getCustomeruseflag()) {
            boolean flag = medicationrecordService.insert(medicationrecord);
            if (flag) {
                r = new ResultBean(200, true, "新增成功，编号为" + medicationrecord.getMedicationrecordid(), null);
            } else {
                r = new ResultBean(5005, false, "创建失败", null);
            }
        }else {
            r = new ResultBean(5006, false, " 创建失败，客户不存在或已被删除", null);
        }
        return r;
    }
    /**
     * 新增用药记录
     *
     * @return
     * @throws ParseException
     */
    @PostMapping(value = "/update/{medicationrecordid}")
//    @ResponseBody
    public ResultBean update(@PathVariable("medicationrecordid") String medicationrecordid,@Validated MedicationrecordConve medicationrecordConve, BindingResult bindingResult) {
        ResultBean r = null;
        if(bindingResult.hasErrors()){
            //方法一：将无法通过数据校验的信息，合并成一个字符串，返回给前端
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
            ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            //方法二：将所有无法通过数据校验的信息集合，直接返回给前端，让前端自行处理
            // r = new ResultBean(5004,false,"部门赋值失败",bindingResult.getFieldErrors());
            return r;
        }
        Medicationrecord medicationrecord = Medicationrecord.builder()
                .customerid(Integer.valueOf(medicationrecordConve.getCustomerid()))
                .medicationrecorddispenser(medicationrecordConve.getMedicationrecorddispenser())
                .medicationrecorddosage(medicationrecordConve.getMedicationrecorddosage())
                .medicationrecorddrugname(medicationrecordConve.getMedicationrecorddrugname())
                .medicationrecordid(Integer.valueOf(medicationrecordid))
                .medicationrecordmethod(medicationrecordConve.getMedicationrecordmethod())
                .medicationrecordshipper(medicationrecordConve.getMedicationrecordshipper()).build();
        Customer customer = customerService.selectByPrimaryKey(medicationrecord.getCustomerid());
        if(customer!=null&&customer.getCustomeruseflag()) {
            boolean flag = medicationrecordService.updateByPrimaryKeySelective(medicationrecord);
            if (flag) {
                r = new ResultBean(200, true, "修改成功", null);
            } else {
                r = new ResultBean(5005, false, "修改失败", null);
            }
        }else {
            r = new ResultBean(5006, false, " 修改失败，客户不存在或已被删除", null);
        }
        return r;
    }
}
